/*
 * @Author: chenr 526963089@qq.com
 * @Date: 2023-02-13 09:39:03
 * @LastEditors: chenr 526963089@qq.com
 * @LastEditTime: 2023-02-14 11:10:15
 * @Description: 
 */
const responseBody: any = {
  message: '',
  timestamp: 0,
  data: null,
  code: 0,
  success: true,
};

interface BuilderInterface<T> {
  data: T;
  message?: string;
  code?: number;
  headers?: any;
}

export const builder = <T>({
  data,
  message,
  code = 0,
  headers = {},
}: BuilderInterface<T>) => {
  responseBody.data = data;
  if (message !== undefined && message !== null) {
    responseBody.message = message;
  }
  if (code !== undefined && code !== 0) {
    responseBody.code = code;
    responseBody.success = code === 200;
    responseBody._status = code;
  }
  if (
    headers !== null &&
    typeof headers === 'object' &&
    Object.keys(headers).length > 0
  ) {
    responseBody._headers = headers;
  }
  responseBody.timestamp = new Date().getTime();
  return responseBody;
};

export const getQueryParameters = (options: any) => {
  const url = options.url;
  const search = url.split('?')[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
};

export const getBody = (options: any) => {
  return options.body && JSON.parse(
    '{"' +
      decodeURIComponent(options.body)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
  // return options.body && JSON.parse(options.body);
};
